const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const xlsx = require('node-xlsx');

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

router.post('/uploadfile', async(ctx, next)=>{
    // 上传单个文件
    const file = ctx.request.files.file; //获取上传文件
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    
    let filePath = path.join(path.resolve(__dirname , '..'),'public/upload/') + `${file.name}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
    return ctx.body = JSON.stringify({filePath})
})

router.post('/filedata', async (ctx, next) => {
  console.log(ctx.request.body.filePath)
  let filePath = ctx.request.body.filePath
  var list = xlsx.parse(filePath);
  console.log(list[0])
  console.log(list[0].data)
  return ctx.body = {
    data:list
  }
})


module.exports = router
